package linwen.wang.application.impl.v1;

import linwen.wang.application.OrderDetailService;
import linwen.wang.domain.AddressConvertMapper;
import linwen.wang.domain.OrderConvertMapper;
import linwen.wang.domain.ProductConvertMapper;
import linwen.wang.domain.UserConvertMapper;
import linwen.wang.entity.Address;
import linwen.wang.entity.Order;
import linwen.wang.entity.Product;
import linwen.wang.entity.User;
import linwen.wang.service.IAddressService;
import linwen.wang.service.IOrderService;
import linwen.wang.service.IProductService;
import linwen.wang.service.IUserService;
import linwen.wang.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
public class OrderDetailServiceV1 implements OrderDetailService {
    @Autowired
    private IUserService userService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IAddressService addressService;

    @Autowired
    private OrderConvertMapper orderConvertMapper;

    @Autowired
    private AddressConvertMapper addressConvertMapper;

    @Autowired
    private UserConvertMapper userConvertMapper;

    @Autowired
    private ProductConvertMapper productConvertMapper;

    @Override
    public List<? extends OrderDetailVO> getByUserId(Long userId) {
        List<Order> orders = orderService.getByUserId(userId);
        return orders.stream()
                .map(order -> convertToOrderDetailVO(order))
                .collect(toList());
    }

    private OrderDetailVOV1 convertToOrderDetailVO(Order order) {
        OrderVO orderVO = orderConvertMapper.orderConvertOrderVO(order);

        OrderDetailVOV1 orderDetailVO = new OrderDetailVOV1(orderVO);

        Address address = this.addressService.getById(order.getAddressId());
        AddressVO addressVO = addressConvertMapper.addressConvertAddressVO(address);
        orderDetailVO.setAddress(addressVO);

        User user = this.userService.getById(order.getUserId());
        UserVO userVO = this.userConvertMapper.userConvertUserVO(user);
        orderDetailVO.setUser(userVO);

        Product product = this.productService.getById(order.getProductId());
        ProductVO productVO = this.productConvertMapper.productConvertProductVO(product);
        orderDetailVO.setProduct(productVO);
        return orderDetailVO;
    }
}
